package com.itjeffrey.autocode.websocket;

import com.itjeffrey.autocode.util.ACBaseUtil;
import com.itjeffrey.autocode.util.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import java.io.IOException;

/**
 * WebSocketServer抽象类
 */
@Slf4j
public abstract class BaseSocketServer implements SocketServer {

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    protected Session session;

    //访问token
    protected String token;

    //客户端Ip
    protected String ip;

    /**
     * 连接建立成功调用的方法
     */
    @Override
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        String ip = WebSocketUtil.getIpByWebSocket(session);
        log.debug("客户端IP：" + ip);
        this.ip = ip;
        if (this instanceof TokenWebSocketServer) {
            synchronized (BaseSocketServer.class) {
                WebSocketServerContainer.addSocketServerByIP(ip, this);
            }
        } else if (this instanceof WebSocketServer) {
            synchronized (BaseSocketServer.class) {
                WebSocketServerContainer.addSocketServerByIP(ip, this);
            }
        }
        log.debug("[{}]客户端连接的websocket数量：{} -> {}", ip, WebSocketServerContainer.getByIP(ip).size(),
                WebSocketServerContainer.getByIP(ip).toString());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    @Override
    public void onMessage(String message, Session session) {
        log.debug("收到[{}]客户端的消息：{}", ip, message);
    }

    /**
     * 发送消息
     *
     * @param message
     * @throws IOException
     */
    @Override
    public void sendMessage(String message) throws IOException {
        /**
         websocket  session发送文本消息有两个方法：getAsyncRemote()和
         getBasicRemote()  getAsyncRemote()和getBasicRemote()是异步与同步的区别，
         大部分情况下，推荐使用getAsyncRemote()。*/
        this.session.getBasicRemote().sendText(message); //同步发送
        log.debug("{}已发送消息[“{}”]到达[{}]客户端！", ACBaseUtil.getObjClass(this), message, ip);
    }

    /**
     * 错误处理
     *
     * @param session
     * @param error
     */
    @Override
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("与[{}]客户端的连接出现异常！", ip);
        error.printStackTrace();
    }

    /**
     * 连接关闭调用的方法
     */
    @Override
    @OnClose
    public void onClose() {
        WebSocketServerContainer.removeSocketServer(ip, ACBaseUtil.getObjClass(this));
        log.debug("[{}]客户端的{}连接已正常关闭！", ip, ACBaseUtil.getObjClass(this));
    }
}
